from pymongo import MongoClient
import threading
import sys



# # 获取数据库
# db = client['bbp']

# # 获取集合
# collection = db['test']

# # 获取文档
# collection.find_one({'id': '1'})
# res = collection.find()
# for item in res:
#     print(item)

class DB:

    _instance_lock = threading.Lock()

    def __init__(self):
        self.__db = None
        self.getDb()

    # 单例模式
    def __new__(cls, *args, **kwargs):
        if not hasattr(DB, "_instance"):
            with DB._instance_lock:
                if not hasattr(DB, "_instance"):
                    DB._instance = object.__new__(cls)
        return DB._instance

    def getDb(self):
        if self.__db is None:
            # 建立连接
            try:
                client = MongoClient('127.0.0.1', port=27017)
                # 获取数据库
                db = client['bbp']
                self.__db=db
            except Exception as e:
                return None
        return self.__db


